$(document).ready(function() {
    var table = $('#activity_table').DataTable({
        // "className": 'display stripe hover order-column row-border',
        "jQueryUI":true,
        "paging": true,// 启用分页
        "lengthMenu":[10,20],// 每页显示条目数选项
        "pageLength": 10,// 默认每页显示条目数
        "searching": true, //启用搜索
        "ordering": true, // 启用排序
        "order": [[0, "asc"]], // 默认按第一列升序排序
        "responsive": true, //响应式
        "oLanguage":{ //语言转换
            "sInfo": "显示第 _START_ 至 _END_ 项结果，共_TOTAL_ 项",
            "sLengthMenu": "每页显示 _MENU_ 项结果",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            }
        },
        "columnDefs": [{
            "targets": -1, // 最后一列
            "data": null,
            "orderable": false, // 禁止排序
            "searchable": false, // 禁止搜索
            "defaultContent": "", // 默认内容为空
            "className": "dt-center", // DataTables内置的居中类
            "render": function(data, type, row, meta){
                return `
                        <div class="action-buttons">
                            <button class="btn-view" title="统计" data-id="${row[0]}">
                                <i class="fas fa-area-chart"></i>
                            </button>
                            <button class="btn-edit" title="编辑" data-id="${row[0]}">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn-delete" title="删除" data-id="${row[0]}">
                                <i class="fas fa-trash-alt"></i>
                            </button>
                            <button class="btn-qrcode" title="二维码" data-id="${row[0]}">
                                <i class="fas fa-qrcode"></i>
                            </button>
                        </div>
                    `;
            }
        }],
        "ajax":{
            type:'get',
            url : url+"getActivityList",
            headers: {
                'content-type': 'application/json',
                'authorization':"Bearer " + token
            },
            data:{
                "institution_id":"111",
                "is_admin": "true"
            },
            "dataSrc": "data.activities"
        },
        "columns": [
            { data: "Name" },
            {
                data: "StartTime"
                // render: function(data) {
                //     return new Date(data).toLocaleString(); // 格式化为本地日期时间
                // }
            },
            {
                data: "EndTime"
                // render: function(data) {
                //     return new Date(data).toLocaleString(); // 格式化为本地日期时间
                // }
            },
            { defaultContent: "" }
        ]
    });
    // 统计按钮点击事件
    $('#activity_table').on('click', '.btn-view', function() {
        var data = table.row($(this).parents('tr')).data();
        $("#titleText").html("统计分析");
        var contentHtml = `
                <div class="topArea">
                    <div class="statistics">
                        <p>总参与人数</p>
                        <p>900</p>
                    </div>
                    <div class="statistics">
                        <p>平均满意度</p>
                        <p>90%</p>
                    </div>
                </div>
                <div class="bottomArea">
                    <canvas id="subItemScore"></canvas>
                </div>`;
        $(".popupContent").html(contentHtml);
        draw();
        $(".popup").css("display", "block");
    });
    //生成柱状图
    var draw = function (){
        const ctx = $('#subItemScore');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['综合服务', '客户服务', '秩序维护', '工程维修', '保洁绿化'],
                datasets: [{
                    label: '满意度',
                    data: [12, 19, 3, 5, 2],
                    backgroundColor: [
                        'rgba(255, 99, 132, 0.2)',
                        'rgba(54, 162, 235, 0.2)',
                        'rgba(255, 206, 86, 0.2)',
                        'rgba(75, 192, 192, 0.2)',
                        'rgba(153, 102, 255, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                        'rgba(54, 162, 235, 1)',
                        'rgba(255, 206, 86, 1)',
                        'rgba(75, 192, 192, 1)',
                        'rgba(153, 102, 255, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 编辑按钮点击事件
    $('#activity_table').on('click', '.btn-edit', function() {
        var data = table.row($(this).parents('tr')).data();
        $("#titleText").html("编辑活动");
        var contentHtml = `
            <div class="inputArea a_name">
                <p>活动名称</p>
                <input type="text" id="a_name"/>
            </div>
            <div class="inputArea">
                <div class="a_datetime">
                    <p>开始时间</p>
                    <input type="datetime-local" id="start_time" />
                </div>
                <div class="a_datetime">
                    <p>结束时间</p>
                    <input type="datetime-local" id="end_time" />
                </div>
            </div>
            <button id="submit">提交</button>`;
        $(".popupContent").html(contentHtml);
        $("#a_name").val(data.Name);
        $("#start_time").val(data.StartTime.substring(0,data.StartTime.length -4));
        $("#end_time").val(data.EndTime.substring(0,data.EndTime.length -4));
        $("#submit").off('click').on('click', function() {
            updateActivity_submit(data.ID,data.State);
        });
        $(".popup").css("display", "block");
    });

    // 删除按钮点击事件
    $('#activity_table').on('click', '.btn-delete', function() {
        var data = table.row($(this).parents('tr')).data();
        $("#titleText").html("删除活动");
        var contentHtml = `
                <div class="deleteConfirm">
                    <p>您确定要删除【<span>${data.Name}</span>】吗？</p>
                    <button class="closeBtn">取消</button>
                    <button class="confirmBtn">确认</button>
                </div>`;
        $(".popupContent").html(contentHtml);
        $(".closeBtn").off("click").on('click',function (){
            $(".popup").css("display", "none");
        });
        $(".confirmBtn").off("click").on('click',function (){
            deleteActivity(data.ID);
            $(".popup").css("display", "none");
            table.row($(this).parents('tr')).remove().draw();
        });
        $(".popup").css("display", "block");
    });
    //删除活动接口
    var deleteActivity = function (id){
        $.ajax({
            type:'post',
            url : url+"deleteActivity",
            headers: {
                'content-type': 'application/json',
                'authorization':"Bearer " + token
            },
            data:JSON.stringify({
                "id":id
            }),
            success: function(data) {
                console.log("创建活动结果：",data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("请求失败：", {
                    Status: jqXHR.status,
                    Response: jqXHR.responseJSON || jqXHR.responseText,
                    Error: errorThrown
                });
            }
        });
    }

    // 二维码按钮点击事件
    $('#activity_table').on('click', '.btn-qrcode', function() {
        var data = table.row($(this).parents('tr')).data();
        alert('二维码: ' + data[0]);
    });
    //新建活动按钮点击事件
    $('#createActivity').on('click', function() {
        $("#titleText").html("创建活动");
        var contentHtml = `
            <div class="inputArea a_name">
                <p>活动名称</p>
                <input type="text" id="a_name"/>
            </div>
            <div class="inputArea">
                <div class="a_datetime">
                    <p>开始时间</p>
                    <input type="datetime-local" id="start_time"/>
                </div>
                <div class="a_datetime">
                    <p>结束时间</p>
                    <input type="datetime-local" id="end_time"/>
                </div>
            </div>
            <button id="submit">提交</button>`;
        $(".popupContent").html(contentHtml);
        $("#submit").off('click').on('click', function() {
            createActivity_submit();
        });
        $(".popup").css("display", "block");
    });
    //创建活动提交接口
    var createActivity_submit = function (){
        var a_name = $('#a_name').val();
        var start_time = new Date($('#start_time').val()).getTime();
        var end_time = new Date($('#end_time').val()).getTime();
        $.ajax({
            type:'post',
            url : url+"createActivity",
            headers: {
                'content-type': 'application/json',
                'authorization':"Bearer " + token
            },
            data:JSON.stringify({
                "institution_id":institution_id,
                "name":a_name,
                "start_time": start_time,
                "end_time": end_time
            }),
            success: function(data) {
                console.log("创建活动结果：",data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("请求失败：", {
                    Status: jqXHR.status,
                    Response: jqXHR.responseJSON || jqXHR.responseText,
                    Error: errorThrown
                });
            }
        });
    }
    //编辑活动提交接口
    var updateActivity_submit = function (id,state){
        var a_name = $('#a_name').val();
        var start_time = new Date($('#start_time').val()).getTime();
        var end_time = new Date($('#end_time').val()).getTime();
        $.ajax({
            type:'put',
            url : url+"updateActivity/"+id,
            headers: {
                'content-type': 'application/json',
                'authorization':"Bearer " + token
            },
            data:JSON.stringify({
                // "id":id,
                "name":a_name,
                "start_time": start_time,
                "end_time": end_time,
                "state": state
            }),
            success: function(data) {
                console.log("编辑活动结果：",data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("请求失败：", {
                    Status: jqXHR.status,
                    Response: jqXHR.responseJSON || jqXHR.responseText,
                    Error: errorThrown
                });
            }
        });
    }
    //关闭弹窗
    $(".close").on('click', function() {
        $(".popup").css("display", "none");
    });
});